package sc.tcp.impl;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

import sc.helper.Constants;
import sc.helper.Helper;
import sc.tcp.TCPGateway;
import sc.udp.UDPGateway;


public class TCPReceiver implements Runnable {

	private Logger logger = Logger.getLogger(this.getClass());

	private final int PACKET_SIZE = 64*1024;
	
	private boolean isRunning = true;
	
	private UDPGateway udpGW;
	
	private TCPGateway tcpGW;
	
	public TCPReceiver(UDPGateway udpGW, TCPGateway tcpGW) {
		this.udpGW = udpGW;
		this.tcpGW = tcpGW;
		logger.debug("Created");
	}
	
	public void run() {
		logger.debug("Started");
		while(isRunning) {
			try {
//				logger.debug("Waiting for TCP packet...");
				
//				InputStream in = socket.getInputStream();
//				
//				byte[] lenByte = new byte[4];
//				in.read(lenByte);
//				int len = lenByte[0]*256 + lenByte[1];
//				int port = lenByte[2]*256 + lenByte[3];
//				
//				byte[] newData = new byte[len];
//				for (int i=0; i<len; i++) {
//					newData[i] = (byte)in.read();
//				}

				byte[] data = tcpGW.read();
				int port = (((int)data[0])&0x000000ff)*256 + (((int)data[1])&0x000000ff);
				
				byte[] newData = new byte[data.length-2];
				for (int i=0; i<newData.length; i++) {
					newData[i] = data[i+2];
				}
				
				SocketAddress destAddress = new InetSocketAddress(Constants.UDP_SEND_HOST, port);
				DatagramPacket packet = new DatagramPacket(newData, newData.length, destAddress);
				udpGW.getSocket(port).send(packet);

//				logger.debug("TCP (" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() 
//							 + ") -> UDP (" + destAddress + "):\n" + Helper.byteArrayToHexString(newData) );
				logger.debug("TCP -> UDP (" + port + "):\n" + Helper.byteArrayToHexString(newData) );
				
			} catch (IOException e) {
				logger.debug("Disconnected, closing...");
				isRunning = false;
			}
		}
		logger.debug("Closed");
	}
	
	public synchronized void shutdown() {
		isRunning = false;
	}
	
}
